﻿using JT808.Protocol;
using JT808.Protocol.Extensions;
using JT808.Protocol.MessageBody;
using SuperSocket.SocketEngine;
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Globalization;
using System.Net;
using System.Net.Sockets;
using System.Text;
using System.Text.RegularExpressions;
using System.Threading;
using System.Threading.Tasks;
using System.Windows.Forms;

namespace JT808_win
{
    public partial class ServerWin : Form
    {
        public ServerWin()
        {
            InitializeComponent();
        }
        private JT808Server appServer;
        private void button1_Click(object sender, EventArgs e)
        {
            //声明bootStrap实例
            var bootstrap = BootstrapFactory.CreateBootstrap();
            //bootstrap.
            int port = int.Parse(txtPort.Text);
            if (appServer != null && appServer.State == SuperSocket.SocketBase.ServerState.Running)
                return;
            var config = new SuperSocket.SocketBase.Config.ServerConfig()
            {
                Name = "SuperSocketServer",
                ServerTypeName = "SuperSocketServer",
                ClearIdleSession = false, //60秒执行一次清理90秒没数据传送的连接
                ClearIdleSessionInterval = 60,
                IdleSessionTimeOut = 90,
                MaxRequestLength = 10000, //最大包长度
                Ip = "Any",
                Port = port,
                MaxConnectionNumber = 10000,//最大允许的客户端连接数目
            };
            appServer = new JT808Server(app_NewSessionConnected, app_SessionClosed);
            //移除请求处理方法的注册，因为它和命令不能同时被支持：
            //appServer.NewRequestReceived -= App_NewRequestReceived;
            //appServer.NewRequestReceived += App_NewRequestReceived;
            appServer.JT808NewMsgReceived -= JT808NewMsgReceived;
            appServer.JT808NewMsgReceived += JT808NewMsgReceived;
            appServer.JT808MsgResponse -= JT808MsgResponse;
            appServer.JT808MsgResponse += JT808MsgResponse;
            appServer.Setup(config);
            if (!appServer.Start())
            {
                showLog("初始化服务失败" + '\n');
            }
            else
            {
                btnStart.Enabled = false;
                btnClose.Enabled = true;
            }
        }
        void JT808NewMsgReceived(JT808Session session, JT808RequestInfo requestInfo)
        {
            showLog("收到：" + DecodeUnicode(JT880Tools.JT808Serializer.Analyze(requestInfo.Data)),2);
        }
        void JT808MsgResponse(JT808Session session, JT808RequestInfo requestInfo, JT808Package responsePackage)
        {
            showLog("回复：" + DecodeUnicode(JT880Tools.JT808Serializer.Analyze(JT880Tools.JT808Serializer.Serialize(responsePackage))),1);
        }
        private string DecodeUnicode(string s)
        {
            Regex reUnicode = new Regex(@"\\u([0-9a-fA-F]{4})", RegexOptions.Compiled);

            return reUnicode.Replace(s, m =>
            {
                short c;
                if (short.TryParse(m.Groups[1].Value, System.Globalization.NumberStyles.HexNumber, CultureInfo.InvariantCulture, out c))
                {
                    return "" + (char)c;
                }
                return m.Value;
            });
        }
        private void showLog(string logMsg,int type=0)
        {
            this.BeginInvoke(new Action(() =>
            {
                switch(type)
                {
                    case 0:
                        msgLog.SelectionColor = Color.Black;
                        break;
                    case 1:
                        msgLog.SelectionColor = Color.Red;
                        break;
                    case 2:
                        msgLog.SelectionColor = Color.Green;
                        break;
                    default:
                        break;
                }
                msgLog.AppendText(logMsg + '\n');
            }));
        }

        //客户端断开
        void app_SessionClosed(JT808Session session, SuperSocket.SocketBase.CloseReason value)
        {
            showLog($"客户端{session.SessionID}已断开，原因：{value.ToString()}");
        }
        //客户端连接
        void app_NewSessionConnected(JT808Session session)
        {
            showLog($"客户端{session.SessionID}已连接");
        }

        private void btnClose_Click(object sender, EventArgs e)
        {
            if(appServer!=null)
            {
                appServer.Stop();
                btnStart.Enabled = true;
                btnClose.Enabled = false;
            }
        }
    }
}
